package com.guchenghao.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guchenghao.dto.UserDto;
import com.guchenghao.entity.Comment;
import com.guchenghao.entity.User;
import com.guchenghao.mapper.CommentMapper;
import com.guchenghao.mapper.UserMapper;
import com.guchenghao.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @User 20675
 * @Author gch
 * @Date 2025/3/31 19:51
 * @Description <br />
 * <p>
 * <br />
 */
@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Page<Comment> commentWithUserDtoPage(Integer articleId, Integer pageNum, Integer pageSize) {
        // 根据文章id对评论进行分页
        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
        Page<Comment> page = new Page<>(pageNum, pageSize);
        commentQueryWrapper.orderByDesc("comment_date");
        commentQueryWrapper.eq("article_id", articleId);
        Page<Comment> commentPage = commentMapper.selectPage(page, commentQueryWrapper);
        // 为每条评论查询对应的用户信息
        for (Comment comment : commentPage.getRecords()) {
            Integer userId = comment.getUserId();
            QueryWrapper<User> userDtoQueryWrapper = new QueryWrapper<>();
            userDtoQueryWrapper.eq("user_id", userId);
            User user = userMapper.selectOne(userDtoQueryWrapper);
            // 去除用户隐私信息
            comment.setUserDto(BeanUtil.copyProperties(user, UserDto.class));
        }
        return commentPage;
    }

    @Override
    public Boolean saveComment(Comment comment) {
        return commentMapper.insert(comment) > 0;
    }
}
